package qmm.servlet.admin;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSON;

import qmm.dao.GoodsDao;
import qmm.dao.impl.GoodsDaoImpl;

@MultipartConfig
@WebServlet("/admin/GoodsImgServlet")
public class GoodsImgServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	public GoodsImgServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//设置请求字符集
		response.setCharacterEncoding("utf-8");//设置响应字符集
		int id = Integer.parseInt(request.getParameter("id"));
		System.out.println(id);
		//1、获得Part对象
		Part part = request.getPart("file");
		//2、获取上传文件名
		String filename = part.getSubmittedFileName();
		System.out.println(filename);
		//3、设置文件存储位置
		String path = request.getServletContext().getRealPath("/upload/"+filename);
		System.out.println(path);
		//4、写入文件到指定目录
		part.write(path);
		
		GoodsDao dao = new GoodsDaoImpl();
		dao.changeImg(id, filename);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("code", 0);
		String json = JSON.toJSONString(map);
		response.getWriter().write(json);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
}
